package com.bw.cinema

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.VerticalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.bw.cinema.entity.MutilTypeEntity
import com.bw.cinema.entity.MutilVideoEntity
import com.bw.cinema.intent.CinemaIntent
import com.bw.cinema.viewmodel.CinemaViewModel
import com.bw.lib_common.NavPath
import com.bw.lib_miv.BaseBox
import com.bw.lib_miv.IUiState
import com.bw.lib_miv.RequestType
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch


@Composable
fun CinemaPage(
    navHostController: NavHostController,
    vm: CinemaViewModel = hiltViewModel(),
    scope: CoroutineScope = rememberCoroutineScope()
) {

    val topList = remember {
        SnapshotStateList<MutilTypeEntity>()
    }

    var topState by remember {
        mutableStateOf(false)
    }

    LaunchedEffect(key1 = "", block = {
        scope.launch {
            vm.uiState.collect {
                when (it) {

                    is IUiState.OnSuccess -> {
                        if (it.type == RequestType.MUTIL_TYPE) {
                            topList.clear()
                            topList.addAll(it.data as Collection<MutilTypeEntity>)
                            topState = true
                        }
                    }

                    is IUiState.OnFailed -> {
                        Log.d("TagA", "获取类型失败: ${it.msg}")
                    }

                    else -> {}
                }
            }
        }
        vm.sendIntent(CinemaIntent.getMutilType)
    })


    Column(
        Modifier
            .fillMaxWidth()
            .fillMaxHeight()
    ) {
        BaseBox(title = "放映室")

        if (topState) {
            tabBar(navHostController = navHostController, list = topList)
        }

    }
}


@OptIn(ExperimentalFoundationApi::class)
@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun tabBar(
    navHostController: NavHostController,
    list: List<MutilTypeEntity>,
) {
    var selector by remember {
        mutableStateOf(0)
    }

    val pageState = rememberPagerState {
        list.size
    }


    Column(
        Modifier
            .fillMaxWidth()
            .padding(5.dp)
    ) {
        ScrollableTabRow(
            selectedTabIndex = selector,
            edgePadding = 16.dp
        ) {
            list.forEachIndexed { index, title ->
                Tab(
                    selected = selector == index,
                    onClick = {
                        selector = index
                    },
                    text = {
                        Text(text = "${title.typename}")
                    }
                )
            }
        }

        Column(Modifier.fillMaxWidth()) {
            getSubType(navHostController = navHostController, list = list[selector])
        }
    }
}


@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun getSubType(
    navHostController: NavHostController,
    list: MutilTypeEntity,
    scope: CoroutineScope = rememberCoroutineScope(),
    vm: CinemaViewModel = hiltViewModel()
) {
    val typeList = remember {
        SnapshotStateList<MutilTypeEntity>()
    }

    scope.launch {
        vm.uiState.collect {
            when (it) {

                is IUiState.OnSuccess -> {
                    if (it.type == RequestType.SUB_MUTIL_TYPE) {
                        typeList.clear()
                        typeList.addAll(it.data as Collection<MutilTypeEntity>)
                        Log.d("TagA", "video: $typeList")
                    }
                }

                is IUiState.OnFailed -> {
                    Log.d("TagA", "获取二级类型失败")
                }

                else -> {}
            }
        }
    }
    vm.sendIntent(CinemaIntent.getSubMutilType(list.id))

    //数据
    LazyVerticalGrid(columns = GridCells.Fixed(4), Modifier.fillMaxWidth()) {
        items(typeList) {
            Text(
                text = it.typename,
                textAlign = TextAlign.Center,
                modifier = Modifier
                    .padding(start = 10.dp, end = 10.dp, top = 5.dp, bottom = 5.dp)
                    .background(
                        Color(0xFFF39C9C)
                    )
                    .clickable {
                        vm.sendIntent(CinemaIntent.getMutilVideo(1, 10, it.id))
                    }
            )
        }
    }

    Column(Modifier.fillMaxWidth()) {
        homeList(navHostController = navHostController)
    }
}

@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun homeList(
    navHostController: NavHostController,
    vm: CinemaViewModel = hiltViewModel(),
    scope: CoroutineScope = rememberCoroutineScope()
) {

    val videoList = remember {
        SnapshotStateList<MutilVideoEntity>()
    }

    var isUse by remember {
        mutableStateOf(false)
    }

    if (!isUse) {
        vm.sendIntent(CinemaIntent.getMutilVideo(1, 10, 20))
        isUse = true
    }

    scope.launch {
        vm.uiState.collect {
            when (it) {

                is IUiState.OnSuccess -> {
                    if (it.type == RequestType.MUTIL_VIDEO) {
                        videoList.clear()
                        videoList.addAll(it.data as Collection<MutilVideoEntity>)
                    }
                }

                is IUiState.OnFailed -> {
                    Log.d("TagA", "获取数据失败: ${it.msg}")
                }

                else -> {}
            }
        }
    }

    LazyVerticalGrid(columns = GridCells.Fixed(2), content = {
        items(videoList) {
            videoList(navHostController = navHostController, entity = it)
        }
    })


}

@Composable
fun videoList(
    navHostController: NavHostController,
    entity: MutilVideoEntity,
    vm: CinemaViewModel = hiltViewModel()
) {

    Column(
        Modifier
            .fillMaxWidth()
            .padding(5.dp)
            .clickable {
                vm.setMutilVideo(entity)
                navHostController.navigate(NavPath.CINEMA_DETAIL)
            }
    ) {

        AsyncImage(
            model = entity.videomainimag, contentDescription = "", contentScale = ContentScale.Crop,
            modifier = Modifier
                .fillMaxWidth()
                .height(200.dp)
        )

        Text(text = entity.title, fontSize = 16.sp)
    }

}